<?php
class User_UserController extends Protox_Controller_Action {

	public function indexAction() {
		$this->_helper->redirector('list', 'user', 'user');
	}

	public function listAction() {
		$this->view->pageTitle = 'Gerenciar usuários';

		$usersDbTable = new User_Model_Users();
		$usersCraftsDbTable = new User_Model_UsersCrafts();
		$sectorsDbTable = new Admin_Model_Sectors();
		$craftsDbTable = new Admin_Model_Crafts();

		$form = new User_Form_UserSearch();
		$request = $this->getRequest();
		
		$this->view->form = $form;

		if ($request->isPost()) {
			if ($form->isValid($request->getPost())) {
				$username = strtolower($form->getValue('username'));
				$fullname = strtolower($form->getValue('fullname'));
				$alias = strtolower($form->getValue('alias'));
				$email = strtolower($form->getValue('email'));
				$date_created = $form->getValue('date_created');
				$item_count_per_page = $form->getValue('item_count_per_page');
				if(empty($item_count_per_page)) {
					$item_count_per_page = 25;
				}

				$select = $usersDbTable->findUsers($username, $fullname, $alias, $email, $date_created);

				if (sizeOf($select) == 0) {
					$this->view->priorityMessenger(sprintf('Nenhum usuário encontrado'), 'alert');
				}
			}
		} else {
			$select = $usersDbTable->getUsers();
		}

		$paginator = Zend_Paginator :: factory($select);
		$page = $this->_getParam('page', 1);
		$paginator->setCurrentPageNumber($page);
		if($item_count_per_page != 0) {
			$paginator->setItemCountPerPage($item_count_per_page);
		}
		

		$this->view->total = count($select);
		$this->view->paginator = $paginator;
	}

	public function viewAction() {
		$this->view->pageTitle = 'Detalhar usuário';
		
		$usersDbTable = new User_Model_Users();
		
		$request = $this->getRequest();
		
		try {

			$id = $this->_getParam('id', 0);

			if (!is_null($id)) {
				$usersDbTable = new User_Model_Users();
				
				$select = $usersDbTable->getUserById($id);

				if (false === $select) {
					$this->view->priorityMessenger(sprintf('Nenhum usuário localizado com id "%s"', $id), 'error');
					return false;
				} else {
					$this->view->data = $select;
					
					if ($request->isPost()) {
						//do something...
					}
				}

			}
		} catch (Exception $ex) {
			return false;
		}
	}

	public function addAction() {
		$this->view->pageTitle = 'Inserir novo usuário';

		$usersDbTable = new User_Model_Users();
		$usersCraftsDbTable = new User_Model_UsersCrafts();
		$sectorsDbTable = new Admin_Model_Sectors();

		$form = new User_Form_UserAdd();
		$request = $this->getRequest();

		$this->view->form = $form;

		try {
			if ($request->isPost()) {
				if ($form->isValid($request->getPost())) {
					
					$username = $form->getValue('username');
					$password = sha1($form->getValue('password'));
					$fullname = $form->getValue('fullname');
					$alias = $form->getValue('alias');
					$email = $form->getValue('email');
					$phone = $form->getValue('phone');
					$date_created = date('Y-m-d');
					$sector = $form->getValue('id_sector');
					$id_craft = $form->getValue('id_craft');

					if (!$usersDbTable->isUniqueUserUsername($username)) {
						$this->view->priorityMessenger(sprintf('Já exite um usuário cadastrado com o nome de usuário "%s"', $username), 'error');
						return false;
					}

					if (!$usersDbTable->isUniqueUserEmail($email)) {
						$this->view->priorityMessenger(sprintf('Já exite um usuário cadastrado com o e-mail "%s"', $email), 'error');
						return false;
					}

					$id_sector = null;
					if ($sector) {
						$sector = substr($sector, strpos($sector, '-') + 1, strlen($sector));
						$sector = $sectorsDbTable->getSectorByName($sector);
						if ($sector['id']) {
							$id_sector = $sector['id'];
							$form->getElement('id_sector')->setValue($id_sector);
						} else {
							$this->view->priorityMessenger(sprintf('O setor "%s" selecionado não foi encontrado', $form->getValue('id_sector')), 'error');
							return false;
						}
					}
					
					$usersDbTable->addUser($username, $password, $fullname, $alias, $email, $phone, $date_created);
					$usersCraftsDbTable->addUserCraft($id_craft, $id_sector, $date_created);

					$this->view->priorityMessenger(sprintf('Usuário cadastrado "%s"', $form->getValue('username')), 'sucess');

					$this->_helper->redirector('list', 'user', 'user');
				} else {
					$form->populate($this->getRequest()->getPost());
				}
			}

		} catch (Exception $ex) {
			return false;
		}
	}

	public function updateAction() {
		$this->view->pageTitle = 'Editar usuário';

		$form = new User_Form_UserUpdate();
		$request = $this->getRequest();

		try {

			$id = $this->_getParam('id', 0);

			if (!is_null($id)) {
				$usersDbTable = new User_Model_Users();
				$usersCraftsDbTable = new User_Model_UsersCrafts();
				$sectorsDbTable = new Admin_Model_Sectors();
				
				$select = $usersDbTable->getUserById($id,$selectUserCrafts=true);

				if (false === $select) {
					$this->view->priorityMessenger(sprintf('Nenhum usuário localizado com id "%s"', $id), 'error');
					return false;
				} else {
					$this->view->form = $form;
					$form->populate($select);
					$this->view->data = $select;

					if ($request->isPost()) {
						if ($form->isValid($request->getPost())) {
							$fullname = $form->getValue('fullname');
							$alias = $form->getValue('alias');
							$email = $form->getValue('email');
							$phone = $form->getValue('phone');
							$sector = $form->getValue('id_sector');
							$id_craft = $form->getValue('id_craft');
							
							$id_sector = null;
							if ($sector) {
								$sector = substr($sector, strpos($sector, '-') + 1, strlen($sector));
								$sector = $sectorsDbTable->getSectorByName($sector);
								if ($sector['id']) {
									$id_sector = $sector['id'];
									$form->getElement('id_sector')->setValue($id_sector);
								} else {
									$this->view->priorityMessenger(sprintf('O setor "%s" selecionado não foi encontrado', $form->getValue('id_sector')), 'error');
									return false;
								}
							}

							$usersDbTable->updateUser($id, $fullname, $alias, $email, $phone);
							$usersCraftsDbTable->updateUserCraft($id,$id_craft, $id_sector);

							$this->view->priorityMessenger(sprintf('Usuário "%s" editado com sucesso', $select['username']), 'sucess');

							$this->_helper->redirector('index', 'user', 'user');

						} else {
							$form->populate($this->getRequest()->getPost());
						}
					}
				}

			}
		} catch (Exception $ex) {
			return false;
		}
	}

	public function deleteAction() {
		$this->view->pageTitle = 'Excluir usuário';

		$form = new User_Form_DeleteConfirm();
		$request = $this->getRequest();

		$id = $this->_getParam('id', 0);
		if (!is_null($id)) {
			$usersDbTable = new User_Model_Users();
			$select = $usersDbTable->getUserById($id);

			if (false === $select) {
				$this->view->priorityMessenger(sprintf('Nenhum usuário localizado com id "%s"', $id), 'error');
				return false;

			} else {
				$this->view->data = $select;

				if ($request->isPost()) {
					if ($form->isValid($request->getPost())) {

						$respYes = $form->getValue('yes');
						$respNo = $form->getValue('no');

						if (!is_null($respYes)) {
							$this->view->priorityMessenger(sprintf('Usuário excluido "%s"', $select['username']), 'sucess');
							$usersDbTable->deleteUser($id);
							$this->_helper->redirector('list', 'user', 'user');
						}

						if (!is_null($respNo)) {
							$this->_helper->redirector('list', 'user', 'user');
						}

					}
				}

				$this->view->form = $form;
			}
		}
	}

	public function printAction() {

	}

}